const fs = require('fs');
const path = require('path');
const url = require('url');

function getMime(extname,callback){
    fs.readFile('./mime.json',(err, data) => {
        if(err) throw err;
        const Mimes = JSON.parse(data.toString());
        const result = Mimes[extname] || 'text/html';
        callback(result);
    })
}

exports.statics = function(req,res,staticPath){
    let pathname = url.parse(req.url).pathname;
    if(pathname === '/'){
        pathname = 'index.html';
    }
    const extname = path.extname(pathname);
    if(pathname !== './favicon.ico'){
        fs.readFile(staticPath + '/' + pathname, function (err,data) {
            if(err){
                console.log('404');
                fs.readFile(staticPath + '/404.html',function (err,data404) {
                    if(err) throw err;
                    res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
                    res.write(data404);
                    res.end();
                })
            }else{
                getMime(extname,function (mime) {
                    res.writeHead(200,{'Content-Type':`${mime};charset=utf8`});
                    res.write(data);
                    res.end();
                })
            }
        })
    }
};